from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
import os
import uuid
import base64
import io
import oss2
from werkzeug.utils import secure_filename
from app.models.user import User
from app import db

# 阿里云OSS配置
OSS_ACCESS_KEY_ID = os.environ.get('OSS_ACCESS_KEY_ID', 'your_access_key_id')
OSS_ACCESS_KEY_SECRET = os.environ.get('OSS_ACCESS_KEY_SECRET', 'your_access_key_secret')
OSS_BUCKET_NAME = os.environ.get('OSS_BUCKET_NAME', 'your_bucket_name')
OSS_ENDPOINT = os.environ.get('OSS_ENDPOINT', 'oss-cn-hangzhou.aliyuncs.com')
OSS_BUCKET_URL = f'https://{OSS_BUCKET_NAME}.{OSS_ENDPOINT}'

upload_bp = Blueprint('upload', __name__)

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@upload_bp.route('/avatar', methods=['POST'])
@jwt_required()
def upload_avatar():
    """上传用户头像到阿里云OSS"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify({'message': '用户不存在'}), 404
        
        # 打印请求信息用于调试
        print(f"Request files: {request.files}")
        print(f"Request form: {request.form}")
        print(f"Request JSON: {request.is_json}")
        
        # 检查是否有文件上传
        if 'avatar' in request.files:
            file = request.files['avatar']
            print(f"File info: filename={file.filename}, content_type={file.content_type}")
            
            if file and file.filename and allowed_file(file.filename):
                # 读取文件内容
                file_content = file.read()
                
                # 生成随机文件名
                extension = file.filename.rsplit('.', 1)[1].lower()
                random_filename = f"{uuid.uuid4().hex}.{extension}"
                
                try:
                    # 初始化阿里云OSS客户端
                    auth = oss2.Auth(OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
                    bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET_NAME)
                    
                    # 上传文件到OSS
                    object_name = f"avatar/{random_filename}"
                    result = bucket.put_object(object_name, io.BytesIO(file_content))
                    
                    if result.status == 200:
                        # 构造访问URL
                        avatar_url = f"{OSS_BUCKET_URL}/{object_name}"
                        
                        # 更新用户头像URL
                        user.avatar = avatar_url
                        db.session.commit()
                        
                        return jsonify({
                            'message': '头像上传成功',
                            'avatar_url': avatar_url
                        }), 200
                    else:
                        return jsonify({'message': f'上传到阿里云OSS失败: {result.status}'}), 500
                except Exception as e:
                    return jsonify({'message': f'上传到阿里云OSS失败: {str(e)}'}), 500
            else:
                return jsonify({'message': '不支持的文件格式'}), 400
        
        # 检查是否有Base64数据
        elif request.is_json:
            data = request.get_json()
            print(f"JSON data: {data}")
            
            if 'avatar' in data and data['avatar']:
                base64_data = data['avatar']
                
                # 从Base64数据创建文件
                if base64_data.startswith('data:image'):
                    # 提取文件扩展名
                    if 'jpeg' in base64_data or 'jpg' in base64_data:
                        extension = 'jpg'
                    elif 'png' in base64_data:
                        extension = 'png'
                    elif 'gif' in base64_data:
                        extension = 'gif'
                    else:
                        extension = 'jpg'  # 默认jpg
                    
                    # 分割数据并获取实际的Base64数据
                    base64_data = base64_data.split(',')[1]
                    
                    # 生成随机文件名
                    random_filename = f"{uuid.uuid4().hex}.{extension}"
                    
                    # 解码Base64数据
                    image_data = base64.b64decode(base64_data)
                    
                    try:
                        # 初始化阿里云OSS客户端
                        auth = oss2.Auth(OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
                        bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET_NAME)
                        
                        # 上传文件到OSS
                        object_name = f"avatar/{random_filename}"
                        result = bucket.put_object(object_name, io.BytesIO(image_data))
                        
                        if result.status == 200:
                            # 构造访问URL
                            avatar_url = f"{OSS_BUCKET_URL}/{object_name}"
                            
                            # 更新用户头像URL
                            user.avatar = avatar_url
                            db.session.commit()
                            
                            return jsonify({
                                'message': '头像上传成功',
                                'avatar_url': avatar_url
                            }), 200
                        else:
                            return jsonify({'message': f'上传到阿里云OSS失败: {result.status}'}), 500
                    except Exception as e:
                        return jsonify({'message': f'上传到阿里云OSS失败: {str(e)}'}), 500
                else:
                    return jsonify({'message': '无效的Base64数据'}), 400
            else:
                return jsonify({'message': '未提供头像数据'}), 400
        else:
            return jsonify({'message': '未提供头像文件'}), 400
            
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'上传失败: {str(e)}'}), 500